package handel

import (
	"book-red/cache"
	"book-red/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func BookAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Book{
		Title:   title,
		Content: content,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "book_add_" + strconv.Itoa(int(data.ID))
	var book model.Book
	model.DB.Where("id=?", data.ID).First(&book)
	jsonData, _ := json.Marshal(book)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func BookDel(c *gin.Context) {
	id := c.Query("id")
	redis_key := "book_del_" + id
	var book model.Book
	cache.Rdb.Del(cache.Ctx, redis_key)
	model.DB.Where("id=?", id).Delete(&book)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func BookList(c *gin.Context) {
	var book []model.Book
	redis_key := "book_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": book,
	})
	return
}
